import { getToken } from '@/utils/cookie'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/oj/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/',
      redirect: '/oj/login', // 前端项目启动时,重定向初始URL到login上
    },
    {
      path: '/oj/layout',
      name: 'layout',
      component: () => import('@/views/Layout.vue'),
      children: [
        {
          path: 'question',
          name: 'question',
          component: () => import('@/views/Question.vue'),
        },
        {
          path: 'cuser',
          name: 'cuser',
          component: () => import('@/views/Cuser.vue'),
        },
        {
          path: 'exam',
          name: 'exam',
          component: () => import('@/views/Exam.vue'),
        },
        {
          path: 'updateExam',
          name: 'updateExam',
          component: () => import('@/views/UpdateExam.vue'),
        }
      ]
    },
  ],
})

router.beforeEach((to, from, next) => {
  // 有token时, 说明用户已经登录, 当用户再次访问登录页面时,直接跳转到大厅
  // 没有token时,如果用户访问的不是登录页面,直接跳转到login
  // token过期的情况在响应拦截器已经判断完成,删除了token
  if (getToken()) {
    if (to.path === '/oj/login') {
      next({ path: '/oj/layout/question' })
    } else {
      next()
    }
  } else {
    if (to.path !== '/oj/login') {
      next({ path: '/oj/login' })
    } else {
      next()
    }
  }
})
export default router
